#include "Command.h"

#include <QMessageBox>

#include "../../IApplication.h"
#include "../ModuleMgr.h"
#include "CmdMgr.h"

Command::Command(int id, const QString& name, int baseCmd)
    : m_id(id), m_baseCmd(baseCmd), m_name(name), m_e_name(name) {
  m_is_authed = true;
}

bool Command::exec(const QString& paramters) const {
  const IModule* module = ModuleMgr::instance().module(m_module);
  if (module) {
    QString param = m_paramers;
    bool raw_param = true;
    if (!param.isEmpty() && param.endsWith("%%param")) {
      param.replace("%%param", paramters);
      raw_param = false;
    } else {
      if (!param.isEmpty()) {
        const int index = param.indexOf(QRegExp("[^%]%[sd]{1}"));
        if (index != -1) {
          param = paramters;
          raw_param = false;
        }
      } else {
        param = paramters;
      }
    }

    QByteArray arr = param.toUtf8();
    QByteArray arr2 = m_name.toUtf8();
    module->execCommand({m_id, m_baseCmd, arr.data(), arr2.data(), raw_param});
  } else
    QMessageBox::information(nullptr, "sumscope", "功能开发中，敬请期待");

  return true;
}

bool Command::exec() {
  // TODO: process it when cmd is not in qbbridge
  // if (m_baseCmd != 0 && false)
  if (!m_paramers.isEmpty()) {
    const IModule* module = ModuleMgr::instance().module(m_module);
    if (module) {
      QByteArray arr = m_paramers.toUtf8();
      QByteArray arr2 = m_name.toUtf8();
      return module->execCommand({m_id, m_baseCmd, arr.data(), arr2.data()});
    } else {
      QMessageBox::information(nullptr, "sumscope", "功能开发中，敬请期待");
      return false;
    }
  }

  return exec(nullptr);
}

bool Command::isAuthed() { return m_is_authed; }

void Command::setModule(const QString& v) {
  m_module = v;
  if (!m_module.isEmpty()) {
    // if the module has not beed loaded
  }
}

void Command::commonPage(int id, int ntype) {
  // TODO
}
